<template>
  <ContainerGroup>
    <Container style="margin-bottom: 10px">
      <FilterForm
        ref="filterForm"
        :elements="filterElements"
        @submit="handleSearch"
        @reset="resetForm"
      />
    </Container>
    <Container height="fill" :scroll-y="true" display="flexY">
      <OperationContainer style="margin-bottom: 10px; display: flex; align-items: center">
        <!-- <div><Button icon="add" @click="handleSave">保存</Button></div> -->
        <div>
          <Button icon="add" @click="handleAdd">新增</Button>
        </div>
        <div>
          <Button icon @click="handleJcBeforeMonth">继承上月</Button>
        </div>

        <!-- <div>
          <Button icon="export" @click="handleUploadTemple">下载模板</Button>
        </div>
        <div><Button icon="export" @click="handleImport">导入</Button></div>-->
        <!-- <div style="margin-left: auto">
          最近一次更新时间：2021-09-22 17:55:55
        </div>-->
      </OperationContainer>
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        border
        :header-cell-style="{ background: '#fafafa', borderColor: '#e7ecf8' }"
        header-row-class-name="ck-table-header"
        row-class-name="ck-table-row"
        size="small"
      >
        <el-table-column align="center" type="index" label width="60" />
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column prop="year" label="年份" />
        <el-table-column prop="month" label="月份" />
        <el-table-column prop="deptCode" label="核算单元编码" />
        <el-table-column prop="deptName" label="核算单元名称" />
        <el-table-column prop="area" label="面积">
          <!-- <template v-slot="scope">
            <el-input
              v-model="scope.row.area"
              size="mini"
              @blur="scope.row.area = handleValidateNumber(scope.row)"
            ></el-input>
          </template>-->
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <i
              class="el-icon-edit-outline"
              style="
                padding-top: 4px;
                font-size: 20px;
                color: #207efa;
                cursor: pointer;
              "
              @click="handleEdit(scope.row)"
            />
            <i
              class="el-icon-delete"
              style="
                padding-top: 4px;
                padding-left: 10px;
                font-size: 20px;
                color: #207efa;
                cursor: pointer;
              "
              @click="handleDelete(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="pageAttr.total"
        :page="pageAttr.currentPage"
        :page-size="pageAttr.pageSize"
        @pagation="pagationChange"
      />
      <!--导入 -->
      <Dialog
        title="导入数据"
        :visible="drVisible"
        :footer-btns="[
          {
            text: '保存',
            type: 'primary',
            trigger: 'confirm',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @cancel="drVisible = false"
        @confirm="handleConfirm"
      >
        <el-form ref="form" :model="formInfo" label-width="100px" size="small">
          <el-form-item label="导入依据列：">
            <el-select v-model="formInfo.edExtraFirstCode" placeholder="请选择" filterable>
              <el-option
                v-for="item in workerPerson"
                :key="item.deptCode"
                :label="item.deptName"
                :value="item.deptCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="文件：">
            <el-upload
              :show-file-list="false"
              class="upload-demo"
              action
              :auto-upload="false"
              :on-change="handlechange"
            >
              <el-button size="mini" type="primary">导入文件</el-button>
              <!-- <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>-->
            </el-upload>
          </el-form-item>
        </el-form>
      </Dialog>
      <!--继承 -->
      <Dialog
        title="继承"
        :visible="jcVisible"
        :footer-btns="[
          {
            text: '保存',
            type: 'primary',
            trigger: 'confirm',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @cancel="jcVisible = false"
        @confirm="handleJcConfirm"
      >
        <el-form ref="form" :model="inheritForm" label-width="100px" size="small">
          <el-form-item label="继承年/月：">
            <el-date-picker
              v-model="inheritForm.jcYearMoth"
              clearable
              size="small"
              type="month"
              placeholder="请选择年月"
              format="yyyy-MM"
              value-format="yyyy-MM"
              :picker-options="expireTimeOptionBm"
            />
          </el-form-item>
          <el-form-item label="选择年月：">
            <el-date-picker
              v-model="inheritForm.chooseYearMonth"
              clearable
              size="small"
              type="month"
              placeholder="请选择年月"
              format="yyyy-MM"
              value-format="yyyy-MM"
              :picker-options="expireTimeChooseBm"
            />
          </el-form-item>
        </el-form>
      </Dialog>
      <!--新增、编辑 -->
      <Dialog
        :title="addEditTile"
        :visible="addEditVisible"
        :footer-btns="[
          {
            text: '保存',
            type: 'primary',
            trigger: 'confirm',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @cancel="addEditVisible = false"
        @confirm="handleAddEditConfirm"
      >
        <el-form ref="form" :model="saveInfor" label-width="100px" size="small">
          <!-- <el-form-item label="年/月：">
            <el-date-picker
              v-model="saveInfor.yearMoth"
              type="month"
              placeholder="选择月"
              value-format="yyyy-MM"
            >
            </el-date-picker>
          </el-form-item>-->
          <el-form-item label="核算单元：">
            <el-select
              v-model="saveInfor.deptCode"
              style="width: 100%"
              placeholder="请选择"
              filterable
            >
              <el-option
                v-for="item in deptDataList"
                :key="item.deptCode"
                :label="item.deptName"
                :value="item.deptCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="面积：">
            <el-input v-model="saveInfor.area" placeholder="请输入" />
          </el-form-item>
        </el-form>
      </Dialog>
    </Container>
  </ContainerGroup>
</template>

<script>
import {
  listYearAndMonth,
  listCusUnitAreaByPage,
  updateCusUnitAreaById,
  deleteCusUnitAreaById,
  extendLastMonth,
  insertCusUnitArea,
  getCusUnitAreaById
} from '../../../utils/apis/integrate/index'
import { Integrate } from '../../../utils/integrate'
import { getDepartmentSource } from '../../../utils/apis/accountingUnit/dept'
import CostVue from '../../accountingData/Cost.vue'
const initYearMonth = ''
export default {
  name: 'Area', // 科室-工资对应
  data() {
    const _this = this
    return {
      expireTimeOptionBm: {
        disabledDate(date) {
          // disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
          return date.getTime() > new Date(_this.$util.currentDate(2)).getTime()
        }
      },
      expireTimeChooseBm: {
        disabledDate(date) {
          // disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
          return date.getTime() > new Date(_this.$util.currentDate(1)).getTime()
        }
      },
      deptDataList: [],
      saveInfor: {
        area: '',
        yearMoth: '',
        deptCode: ''
      },
      addEditTile: '',
      inheritForm: {
        currentYearMonth: '',
        jcYearMoth: '',
        chooseYearMonth: ''
      },
      dateList: [],
      jcVisible: false,
      workerPerson: [],
      formInfo: {},
      drVisible: false,
      addEditVisible: false,
      pageAttr: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      filterElements: [
        {
          key: 'timeType',
          type: 'date-picker',
          label: '年/月',
          mode: 'month',
          type: 'date-picker',
          format: 'yyyy-MM',
          value: this.$util.currentDate(),
          width: 210,
          defaultValue: this.$util.currentDate()
        }
        // {
        //   value: "",
        //   itemLabel: "value",
        //   itemValue: "value",
        //   label: "年/月",
        //   key: "timeType",
        //   type: "Select",
        //   options: [],
        // },
      ],
      tableData: [],
      tableLoading: false,
      newParamList: {},
      rowId: ''
    }
  },
  created() {
    this.getYearMonthList()
    this.getDeptList()
  },
  methods: {
    getDeptList() {
      getDepartmentSource({
        projectId: '1',
        SysId: 'Cost'
      }).then(res => {
        if (res.data.code === 200) {
          this.deptDataList = res.data.data
        }
      })
    },
    handleAddEditConfirm() {
      // 确定
      // if (!this.saveInfor.yearMoth) {
      //   this.$message.warning("请选择年月");
      //   return;
      // }
      if (!this.saveInfor.deptCode) {
        this.$message.warning('请选择核算单元')
        return
      }
      const param = {
        deptCode: this.saveInfor.deptCode,
        deptName: this.deptDataList.find(
          item => item.deptCode == this.saveInfor.deptCode
        ).deptName,
        area: this.saveInfor.area
        // month: this.saveInfor.yearMoth.split("-")[1],
        // year: this.saveInfor.yearMoth.split("-")[0],
      }
      if (this.addEditTile == '新增') {
        insertCusUnitArea(param).then(res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            this.addEditVisible = false
            this.getData(this.newParamList)
          } else {
            this.$message.error(res.data.message)
          }
        })
      } else {
        param.id = this.rowId
        updateCusUnitAreaById(param).then(res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            this.addEditVisible = false
            this.getData(this.newParamList)
          } else {
            this.$message.error(res.data.message)
          }
        })
      }
    },
    handleAdd() {
      this.addEditTile = '新增'
      // this.saveInfor.yearMoth = "";
      this.saveInfor.deptCode = ''
      this.saveInfor.area = ''
      this.addEditVisible = true
    },
    handleEdit(row) {
      // this.saveInfor.yearMoth = "";
      this.saveInfor.deptCode = ''
      this.saveInfor.area = ''
      this.rowId = row.id
      const param = {
        id: row.id
      }
      getCusUnitAreaById(param).then(res => {
        if (res.data.code === 200) {
          // this.saveInfor.yearMoth = `${res.data.data.year}-${res.data.data.month}`;
          this.saveInfor.deptCode = res.data.data.deptCode
          this.saveInfor.area = res.data.data.area
        }
      })
      this.addEditTile = '编辑'
      this.addEditVisible = true
    },
    handleDelete(row) {
      // 删除
      const param = {
        id: row.id
      }
      this.$confirm({
        title: '温馨提示',
        content: '您确定要删除该条数据?',
        okText: '确定',
        cancelText: '取消',
        okFn: () => {
          deleteCusUnitAreaById(param).then(res => {
            if (res.data.code === 200) {
              this.$message.success(res.data.message)
              this.pageAttr.currentPage = 1
              this.getData(this.newParamList)
            } else {
              this.$message.error(res.data.message)
            }
          })
        },
        cancelFn: () => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        }
      })
    },
    handleValidateNumber(row) {
      if (row.area) {
        if (!/^[0-9]+.?[0-9]*$/.test(row.area)) {
          this.$message.warning('请输入数字类型!')
          return 0
        } else {
          const integrate = new Integrate()
          integrate.id = row.id
          integrate.area = row.area
          updateCusUnitAreaById(integrate).then(res => {
            if (res.data.code) {
              this.$message.success(res.data.message)
            } else {
              this.$message.error(res.data.message)
            }
          })
          return row.area
        }
      } else {
        return 0
      }
    },
    handlechange(file, fileList) {
      console.log('file', file)
      console.log('fileList', fileList)
      const fileType = file.name.substr(file.name.lastIndexOf('.')).trim()
      if (fileType !== '.xlsx' && fileType !== '.xls') {
        this.$message.warning('请选择Excel格式的文件导入！')
        this.fileList = []
        return
      }
      const files = file.raw
      const formData = new FormData()
      formData.append('file', files)
      // AddHealthSurveyExcel(formData).then((res) => {
      //   if (res.data.code === 200) {
      //     this.$message.success("导入成功");
      //     this.fileList = [];
      //   } else {
      //     this.$message.error(res.data.message);
      //     this.fileList = [];
      //   }
      // });
    },
    handleConfirm() {},
    getYearMonthList() {
      listYearAndMonth().then(res => {
        if (res.data.code === 200) {
          this.filterElements[0].options = res.data.data
          this.dateList = res.data.data
          this.$nextTick(() => {
            this.initYearMonth = res.data.data[0].value
            // this.filterElements[0].value = res.data.data[0].value;
          })
        }
      })
    },
    handleImport() {
      // 导入
      this.drVisible = true
    },
    handleUploadTemple() {
      // 下载模板
      const parms = {
        deptCode: this.ruleForm.deptCode,
        endDate:
          this.ruleForm.timeDate === '' || this.ruleForm.timeDate === null
            ? ''
            : this.ruleForm.timeDate[1],
        nurseCellCode: this.ruleForm.nurseCellCode,
        pageNum: this.pageInfor.pageNum,
        pageSize: this.pageInfor.pageSize,
        startDate:
          this.ruleForm.timeDate === '' || this.ruleForm.timeDate === null
            ? ''
            : this.ruleForm.timeDate[0],
        yard: this.ruleForm.region
      }
      getManageBedCalculationDtoExcel(parms).then(res => {
        const blob = new Blob([res.data])
        const fileName = '数据报表集管床位计算报表' + '.xlsx'
        const URL = window.URL || window.webkitURL || window.moxURL
        if ('download' in document.createElement('a')) {
          // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName // 命名下载名称
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob) // 表示一个指定的file对象或Blob对象
          document.body.appendChild(elink)
          elink.click() // 点击触发下载
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else {
          // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },
    handleJcConfirm() {
      if (!this.inheritForm.jcYearMoth) {
        this.$message.warning('请选择继承年月')
        return
      }
      if (!this.inheritForm.chooseYearMonth) {
        this.$message.warning('请选择年月')
        return
      }
      const param = {
        lastMonth: this.inheritForm.jcYearMoth.split('-')[1],
        lastYear: this.inheritForm.jcYearMoth.split('-')[0],
        thisMonth: this.inheritForm.chooseYearMonth.split('-')[1],
        thisYear: this.inheritForm.chooseYearMonth.split('-')[0]
      }
      extendLastMonth(param).then(res => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message)
          this.getData(this.newParamList)
          this.jcVisible = false
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    handleJcBeforeMonth() {
      // 继承上月
      this.jcVisible = true
    },
    // 分页
    pagationChange(payload) {
      this.pageAttr.currentPage = payload.page
      this.pageAttr.pageSize = payload.pageSize
      this.getData(this.newParamList)
    },
    getData(val) {
      // 列表
      const integrate = new Integrate()
      if (JSON.stringify(val) !== '{}') {
        integrate.month = val.timeType.split('-')[1]
        integrate.year = val.timeType.split('-')[0]
      } else {
        integrate.month = ''
        integrate.year = ''
      }
      integrate.pageNum = this.pageAttr.currentPage
      integrate.pageSize = this.pageAttr.pageSize
      this.tableLoading = true
      listCusUnitAreaByPage(integrate).then(res => {
        if (res.data.code === 200) {
          this.tableLoading = false
          this.tableData = res.data.data.list
          this.pageAttr.total = res.data.data.total || 0
        }
      })
    },
    resetForm() {
      location.reload()
    },
    handleSearch(value) {
      this.newParamList = value
      this.pageAttr.currentPage = 1
      this.getData(value)
    },
    handleSave() {
      // 保存
    }
  }
}
</script>

<style lang="less" scoped>
.el-table--mini,
.el-table--small,
.el-table__expand-icon {
  font-size: 14px !important;
}

.ck-table-header {
  th {
    background: #fafafa !important;
    height: 48px;
    color: #555555 !important;
  }
}
.pagenation-box {
  display: flex;
  padding-top: 2px;
  justify-content: flex-end;
}
</style>
